package com.usian.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.usian.mapper.LogMapper;
import com.usian.mapper.MemberMapper;
import com.usian.mapper.OrderMapper;
import com.usian.service.IGoodService;
import com.usian.shop.entity.Good;
import com.usian.shop.entity.Log;
import com.usian.shop.entity.Member;
import com.usian.shop.entity.Order;
import com.usian.shop.utils.ResponseResult;
import org.springframework.stereotype.Controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-01-10
 */
@Slf4j
@RestController
@RequestMapping("/good")
public class GoodController {

    @Autowired
    private IGoodService goodService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private LogMapper logMapper;
    @RequestMapping("/findAll")
    public PageInfo findAll(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){
return goodService.findAll(pageNum,pageSize);
    }
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Good good){
        QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gid",good.getGid());
        Good good1 = goodService.getOne(queryWrapper);
        good1.setNum(good1.getNum()-good.getShu());
        try {
            goodService.updateById(good1);
            Order order = new Order();
            order.setGname(good1.getGname());
            order.setOmoney(good.getShu()*good1.getPrice());
            order.setGid(good1.getGid());
            order.setCreatetime(new Date());
            order.setMid(good.getDid());
            orderMapper.inserts(order);
            Member member = memberMapper.selectById(order.getMid());

            Log log = new Log();
            log.setType("消费");
            log.setCmoney(good.getShu()*good1.getPrice());
            log.setBmoney(member.getBmoney());
            log.setHmoney(member.getBmoney()-good.getShu()*good1.getPrice());
            log.setCreatetime(new Date());
logMapper.insert(log);
            return ResponseResult.errorResult(200,"下单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(500,"下单失败");
        }
    }
}
